package cn.tedu.init;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.support.EncodedResource;
import org.springframework.jdbc.datasource.init.ScriptUtils;

import javax.annotation.PostConstruct;
import javax.sql.DataSource;
import java.sql.SQLException;

@SpringBootApplication
public class InitApplication {
    @Autowired
    private DataSource ds;

    public static void main(String[] args) {
        SpringApplication.run(InitApplication.class, args);
    }

    // 初始化数据库
    @PostConstruct
    public void init() throws SQLException {
        exec("sql/seata-server.sql");
        exec("sql/order.sql");
        exec("sql/storage.sql");
        exec("sql/account.sql");
    }

    /*
    mysql 5.x
     */
    private void exec(String sql) throws SQLException {
        // D:\home\lesson\2111\project\seata-at\db-init\src\main\resources\sql\account.sql
        // 用当前类的根路径下,寻找 sql/storage.sql
        ClassPathResource cpr = new ClassPathResource(
                sql, InitApplication.class.getClassLoader());
        EncodedResource resource = new EncodedResource(cpr,"UTF-8");

        // spring jdbc 的,执行sql脚本文件的工具
        ScriptUtils.executeSqlScript(
                ds.getConnection(), resource);
    }
}
